package org.benxiong.iplay.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.model.UserProfile;
import org.benxiong.iplay.ui.fragment.BaseFragment;
import org.benxiong.iplay.util.Constants;
import org.benxiong.iplay.util.GlobalVar;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.MeasurementUtil;
import org.benxiong.iplay.util.ObjectConverter;
import org.benxiong.iplay.util.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.DatePicker;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ProfileEditActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	SharedPreferences			prefs;
	private String[]			lookingForArray;
	private String[]			langArray;
	private String[]			roleValues;
	private String[]			relationArray;
	private String[]			buildArray;
	private String[]			enthArray;
	private DatePickerDialog	dateDialog;
	private Preference			dobPreference;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		addPreferencesFromResource(R.xml.profile_edit_pref);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		initDateDialog();

		ListPreference countryPref = (ListPreference) findPreference("country_list");

		Set<String> keys = Constants.COUNTRY_NAMES.keySet();
		String[] entryValues = new String[keys.size()];
		String[] entries = new String[keys.size()];
		int index = 0;
		for (String str : keys) {
			entryValues[index] = str;
			entries[index] = Constants.COUNTRY_NAMES.get(str);
			index++;
		}
		List<String> countryCodes = Constants.SortedCountryCodesByName();
		countryPref.setEntryValues(countryCodes.toArray(new String[countryCodes.size()]));
		List<String> countryNames = Constants.SortedCountryNames();
		countryPref.setEntries(countryNames.toArray(new String[countryNames.size()]));

		dobPreference = findPreference("dob");
		dobPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				dateDialog.show();
				return false;
			}

		});
		bindLocalData();
	}

	private void bindLocalData() {
		String dobStr = prefs.getString("dob", null);
		findPreference("dob").setSummary(dobStr);

		if (prefs.getString("measure", "1").equals("1")) {
			// inch height
			String inch = prefs.getString("inch", null);
			if (inch != null) {
				findPreference("height").setSummary(MeasurementUtil.inchToTxt(Float.valueOf(inch)));
			}
			findPreference("weight").setSummary(prefs.getString("weightPounds", "0") + "Pounds");
		} else {
			// cm height
			findPreference("height").setSummary(prefs.getString("height", null) + "CM");
			findPreference("weight").setSummary(prefs.getString("weight", "0") + "KG");
		}

		findPreference("status").setSummary(prefs.getString("status", null));
		findPreference("place").setSummary(prefs.getString("place", null));
		String coutrCode = prefs.getString("country_list", null);
		if (coutrCode != null)
			findPreference("country_list").setSummary(Constants.COUNTRY_NAMES.get(coutrCode));
		findPreference("intro").setSummary(prefs.getString("intro", null));
		findPreference("private_intro").setSummary(prefs.getString("private_intro", null));
		findPreference("my_type").setSummary(prefs.getString("my_type", null));
		findPreference("facebook").setSummary(prefs.getString("facebook", null));
		findPreference("twitter").setSummary(prefs.getString("twitter", null));
		findPreference("weibo").setSummary(prefs.getString("weibo", null));
		findPreference("wechat").setSummary(prefs.getString("wechat", null));
		findPreference("instagram").setSummary(prefs.getString("instagram", null));
		findPreference("line").setSummary(prefs.getString("line", null));
		findPreference("kik").setSummary(prefs.getString("kik", null));
		findPreference("nickName").setSummary(prefs.getString("nickName", null));

		int roleIndex = Integer.valueOf(prefs.getString("role_list", "0"));

		roleValues = this.getResources().getStringArray(R.array.role);

		findPreference("role_list").setSummary(roleValues[roleIndex]);

		relationArray = this.getResources().getStringArray(R.array.relationship);
		int relationIndex = Integer.valueOf(prefs.getString("relation_list", "0"));
		findPreference("relation_list").setSummary(relationArray[relationIndex]);

		lookingForArray = this.getResources().getStringArray(R.array.lookingfor);
		langArray = this.getResources().getStringArray(R.array.language);
		// prefs.langArraygetStringSet(arg0, arg1)
		findPreference("lookingfor_list").setSummary(convertIndexToLabel(prefs.getStringSet("lookingfor_list", null), lookingForArray));
		findPreference("language_list").setSummary(convertIndexToLabel(prefs.getStringSet("language_list", null), langArray));

		buildArray = this.getResources().getStringArray(R.array.build);
		int buildIndex = Integer.valueOf(prefs.getString("build_list", "0"));
		findPreference("build_list").setSummary(buildArray[buildIndex]);

		enthArray = this.getResources().getStringArray(R.array.enthnicity);
		int enthIndex = Integer.valueOf(prefs.getString("enthnicity_list", "0"));
		findPreference("enthnicity_list").setSummary(enthArray[enthIndex]);

	}

	private void reqProfileData() {
		RequestParams rParam = new RequestParams();
		rParam.put("username", GlobalVar.userName);

		RequestFactory.getInstance().post(RequestFactory.URL_GET_PROFILE,
				rParam, new AsyncHttpResponseHandler() {

					public void onSuccess(String resp) {
						try {
							JSONObject json = new JSONObject(resp);
							if (shouldProcess(json)) {
								LogX.print(json.toString(2));
								fillProfileData(json);
								bindLocalData();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						// showRequestFailMsg(arg1);
						ToastUtil.toast(arg1);
					}

				});
	}

	private void fillProfileData(JSONObject json) throws JSONException {
		UserProfile profile = ObjectConverter.jsonToUserProfile(json);

		Editor editor = prefs.edit();
		editor.putString("dob", profile.getDob());
		editor.putString("height", profile.getHeight() != null ? profile.getHeight().toString() : null);
		editor.putString("inch", profile.getHeightInch() != null ? profile.getHeightInch().toString() : null);
		editor.putString("measure", profile.getMeasure() != null ? profile.getMeasure().toString() : null);
		editor.putString("weight", profile.getWeight() != null ? profile.getHeightInch().toString() : null);
		editor.putString("weightPounds", profile.getWeightPounds() != null ? profile.getWeightPounds().toString() : null);

		editor.putString("role_list", String.valueOf(profile.getRoleIndex()));
		editor.putString("relation_list", String.valueOf(profile.getRelationshipIndex()));
		editor.putString("build_list", String.valueOf(profile.getBuildIndex()));
		editor.putString("enthnicity_list", String.valueOf(profile.getEthnicityIndex()));

		editor.putString("status", profile.getStatus());
		editor.putString("intro", profile.getIntro());
		editor.putString("private_intro", profile.getPrivateIntro());
		editor.putString("my_type", profile.getMyType());

		editor.putString("kik", profile.getKik());
		editor.putString("nickName", profile.getNickName());
		
		editor.putString("facebook", profile.getFacebook());
		editor.putString("twitter", profile.getTwitter());
		editor.putString("weibo", profile.getWeibo());
		editor.putString("wechat", profile.getWechat());
		editor.putString("instagram", profile.getInstagram());
		editor.putString("line", profile.getLine());
		editor.putString("weibo", profile.getWeibo());
		editor.putString("locality", profile.getPlace());
		editor.putString("country_list", profile.getCountry());

		editor.putStringSet("lookingfor_list", this.intToStringSet(profile.getLookingFor()));
		editor.putStringSet("language_list", this.intToStringSet(profile.getLang()));

		/*
		 * String dobStr = json.getString("dobString");
		 * 
		 * if (dobStr != null && !dobStr.equals("null")) { Date date = new
		 * Date(Long.valueOf(dobStr)); SimpleDateFormat sdf = new
		 * SimpleDateFormat("yyyy-MM-dd"); editor.putString("dob",
		 * sdf.format(date)); }
		 * 
		 * editor.putString("height", json.getString("height"));
		 * editor.putString("inch", json.getString("heightInch"));
		 * editor.putString("measure", json.getString("measure"));
		 * editor.putString("weight", json.getString("weight"));
		 * editor.putString("weightPounds", json.getString("weightPounds"));
		 * editor.putString("role_list", json.getString("roleIndex"));
		 * editor.putString("relation_list",
		 * json.getString("relationshipIndex")); editor.putString("build_list",
		 * json.getString("buildIndex")); editor.putString("enthnicity_list",
		 * json.getString("ethnicityIndex")); editor.putString("status",
		 * json.getString("status")); editor.putString("intro",
		 * json.getString("intro")); editor.putString("private_intro",
		 * json.getString("privateIntro")); editor.putString("my_type",
		 * json.getString("myType"));
		 * 
		 * String str = json.getString("lookingFor");
		 * editor.putStringSet("lookingfor_list", convertStrToSet(str)); //
		 * editor.putString("lookingfor_list", );
		 * editor.putStringSet("language_list",
		 * convertStrToSet(json.getString("lang"))); //
		 * editor.putString("language_list", json.getString("lang"));
		 * editor.putString("facebook", json.getString("facebook"));
		 * editor.putString("twitter", json.getString("twitter"));
		 * editor.putString("weibo", json.getString("weibo"));
		 * editor.putString("wechat", json.getString("wechat"));
		 * editor.putString("instagram", json.getString("instagram"));
		 * editor.putString("line", json.getString("line"));
		 * editor.putString("weibo", json.getString("weibo"));
		 * editor.putString("locality", json.getString("place"));
		 * editor.putString("country_list", json.getString("country"));
		 */

		editor.commit();
	}

	protected boolean shouldProcess(JSONObject json) throws JSONException {
		String code = null;
		code = json.getString("code");
		if (BaseFragment.CODE_SUCCESS.equals(code) || BaseFragment.CODE_OK.equals(code)) {
			return true;
		}

		ToastUtil.toast("Error Code = " + code);
		return false;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

		reqProfileData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#
	 * onSharedPreferenceChanged(android.content.SharedPreferences,
	 * java.lang.String)
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Preference pref = findPreference(key);
		if (pref instanceof EditTextPreference) {
			EditTextPreference etp = (EditTextPreference) pref;
			pref.setSummary(etp.getText());
		} else if (pref instanceof ListPreference) {
			ListPreference lsp = (ListPreference) pref;
			pref.setSummary(lsp.getEntry());
		} else if (pref instanceof MultiSelectListPreference) {
			MultiSelectListPreference lsp = (MultiSelectListPreference) pref;
			String txt = "[";
			if (lsp.getKey().equals("lookingfor_list")) {
				for (CharSequence cs : lsp.getValues()) {
					if (cs.length() > 0 && !"null".equals(cs)) {
						txt += lookingForArray[Integer.valueOf(cs.toString())] + ",";
					}

				}
			} else if (lsp.getKey().equals("language_list")) {
				for (CharSequence cs : lsp.getValues()) {
					if (cs.length() > 0 && !"null".equals(cs)) {
						txt += langArray[Integer.valueOf(cs.toString())] + ",";
					}
				}
			}
			if (txt.length() > 1) {
				txt = txt.substring(0, txt.length() - 1);
			}

			txt += "]";
			pref.setSummary(txt);
		}
	}

	private String convertIndexToLabel(Set<String> strs, String[] data) {
		String txt = "[";
		if (strs == null) {
			return "";
		}
		for (String str : strs) {
			if (str.length() > 0 && !"null".equals(str)) {
				// deal with "null" string, we should remove this data from DB
				// later
				txt += data[Integer.valueOf(str)] + ",";
			}
		}

		if (txt.length() > 1) {
			txt = txt.substring(0, txt.length() - 1);
		}
		txt += "]";
		return txt;
	}

	private ArrayList convertSetToAList(Set<String> strs) {
		ArrayList<String> retList = new ArrayList();
		if (strs == null) {
			return retList;
		}
		for (String str : strs) {
			if ("".equals(str) || "null".equals(str)) {
				continue;
			}
			retList.add(str);
		}
		return retList;
	}

	private Set<String> intToStringSet(List<Integer> list) {
		Set<String> set = new HashSet<String>();
		if (list != null)
			for (Integer i : list) {
				set.add(String.valueOf(i));
			}
		return set;
	}

	private Set<String> convertStrToSet(String str) {
		String[] array = str.split("\\[|\\]|,");
		Set<String> sets = new HashSet<String>();
		for (String data : array) {
			sets.add(data);
		}

		return sets;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuItem save = menu.add(0, 1, 0, "Save");

		save.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		return true;
	}

	private RequestParams buildUpdateParam() {
		RequestParams param = new RequestParams();
		param.put("dobString", prefs.getString("dob", null));
		param.put("height", prefs.getString("height", null));
		param.put("inch", prefs.getString("inch", null));
		param.put("measure", prefs.getString("measure", "0"));
		param.put("weight", prefs.getString("weight", null));
		param.put("weightPounds", prefs.getString("weightPounds", null));
		param.put("roleIndex", prefs.getString("role_list", null));
		param.put("relationshipIndex", prefs.getString("relation_list", null));
		param.put("buildIndex", prefs.getString("build_list", null));
		param.put("ethnicityIndex", prefs.getString("enthnicity_list", null));
		param.put("status", prefs.getString("status", null));
		param.put("place", prefs.getString("place", null));
		param.put("country", prefs.getString("country_list", null));
		param.put("intro", prefs.getString("intro", null));
		param.put("privateIntro", prefs.getString("private_intro", null));
		param.put("myType", prefs.getString("my_type", null));
		Set<String> lookingForS = prefs.getStringSet("lookingfor_list", null);
		param.put("lookingFor[]", convertSetToAList(lookingForS));
		Set<String> langS = prefs.getStringSet("language_list", null);
		param.put("lang[]", convertSetToAList(langS));
		LogX.print("prefs.getString FaceBook ==" + prefs.getString("facebook", null));
		param.put("facebook", prefs.getString("facebook", null));
		param.put("twitter", prefs.getString("twitter", null));
		param.put("weibo", prefs.getString("weibo", null));
		param.put("wechat", prefs.getString("wechat", null));
		param.put("instagram", prefs.getString("instagram", null));
		param.put("line", prefs.getString("line", null));
		param.put("kik", prefs.getString("kik", null));
		param.put("nickName", prefs.getString("nickName", null));
		return param;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		if (item.getItemId() == 1) {
			// save action
			RequestParams rParam = buildUpdateParam();
			RequestFactory.getInstance().post(RequestFactory.URL_UPDATE_PROFILE,
					rParam, new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(Throwable arg0) {
							// TODO Auto-generated method stub
							super.onFailure(arg0);
							LogX.print("====Profile=onFailure====" + arg0.getMessage());
							ToastUtil.toast("Failed to update profile!");
						}

						@Override
						public void onSuccess(String arg0) {
							// TODO Auto-generated method stub
							super.onSuccess(arg0);
							LogX.print("===Profile==onSuccess====" + arg0);
							ToastUtil.toast("Profile updated!");
						}

					});
		}

		return true;
	}

	private void initDateDialog() {
		Calendar calendar = Calendar.getInstance();
		dateDialog = new DatePickerDialog(this,
				dateListener,
				calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
	}

	DatePickerDialog.OnDateSetListener	dateListener	=
																new DatePickerDialog.OnDateSetListener() {
																	@Override
																	public void onDateSet(DatePicker datePicker,
																			int year, int month, int dayOfMonth) {
																		// Calendaræœˆä»½æ˜¯ä»Ž0å¼€å§‹,æ‰€ä»¥monthè¦�åŠ 1
																		String dateStr = year + "-";
																		month = month + 1;
																		if (month < 10) {
																			dateStr += "0";
																		}
																		dateStr += month + "-";
																		if (dayOfMonth < 10) {
																			dateStr += "0";
																		}
																		dateStr += dayOfMonth;

																		LogX.print("Date change to ==" + dateStr);
																		// Date
																		// date
																		// = new
																		// Date(year,
																		// month,
																		// dayOfMonth);
																		prefs.edit().putString("dob", dateStr).commit();
																		dobPreference.setSummary(dateStr);
																	}
																};
}
